<template>
  <div class="outbound-container">
    <!-- 创建出库单按钮 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleCreate">创建出库单</el-button>
    </div>

    <!-- 出库单表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="orderNumber" label="出库单号" width="180" />
      <el-table-column label="客户">
        <template slot-scope="scope">
          {{ getCustomerName(scope.row.customerId) }}
        </template>
      </el-table-column>
      <el-table-column label="商品信息" width="200">
        <template slot-scope="scope">
          <div>{{ getProductInfo(scope.row) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="100" />
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            @click="handlePicking(scope.row)"
            :disabled="scope.row.status !== 0"
          >确认拣货</el-button>
          <el-button
            size="mini"
            type="success"
            @click="handleOutbound(scope.row)"
            :disabled="scope.row.status !== 1"
          >确认出库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

    <!-- 创建出库单对话框 -->
    <el-dialog title="创建出库单" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户">
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select 
            v-model="form.supplierId" 
            placeholder="请选择供应商"
            @change="handleSupplierChange"
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="productCode">
          <el-select 
            v-model="form.productCode" 
            placeholder="请选择商品"
            :disabled="!form.supplierId"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productCode"
              :label="`${item.productName} (${item.productCode})`"
              :value="item.productCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'OutboundOrder',
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      customerOptions: [],
      supplierOptions: [],
      productOptions: [],
      form: {
        customerId: null,
        supplierId: null,
        productCode: '',
        quantity: 1,
        remark: ''
      },
      rules: {
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        productCode: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
    this.fetchCustomers()
    this.fetchSuppliers()
  },
  methods: {
    // 获取出库单列表
    async fetchData() {
      try {
        const res = await request({
          url: '/outbound/page',
          method: 'get',
          params: {
            current: this.currentPage,
            size: this.pageSize
          }
        })
        if (res.code === 200) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      } catch (error) {
        this.$message.error('获取出库单列表失败')
      }
    },

    // 获取客户列表
    async fetchCustomers() {
      try {
        const res = await request({
          url: '/customer/list',
          method: 'get'
        })
        if (res.code === 200) {
          this.customerOptions = res.data
        }
      } catch (error) {
        this.$message.error('获取客户列表失败')
      }
    },

    // 获取供应商列表
    async fetchSuppliers() {
      try {
        const res = await request({
          url: '/supplier/list',
          method: 'get'
        })
        if (res.code === 200) {
          this.supplierOptions = res.data
        }
      } catch (error) {
        this.$message.error('获取供应商列表失败')
      }
    },

    // 供应商变更时获取商品列表
    async handleSupplierChange(supplierId) {
      this.form.productCode = ''
      this.productOptions = []
      if (supplierId) {
        try {
          const res = await request({
            url: `/supplier-product/list/${supplierId}`,
            method: 'get'
          })
          if (res.code === 200) {
            this.productOptions = res.data
          }
        } catch (error) {
          this.$message.error('获取商品列表失败')
        }
      }
    },

    // 获取客户名称
    getCustomerName(customerId) {
      const customer = this.customerOptions.find(item => item.id === customerId)
      return customer ? customer.name : '--'
    },

    // 获取商品信息
    getProductInfo(row) {
      const product = this.productOptions.find(p => p.productCode === row.productCode)
      return product ? `${product.productName} (${row.productCode})` : row.productCode
    },

    // 状态显示
    getStatusType(status) {
      const statusMap = {
        0: 'info',    // STATUS_PENDING - 待拣货
        1: 'warning', // STATUS_PICKED - 已拣货
        2: 'success'  // STATUS_COMPLETED - 已出库
      }
      return statusMap[status] || 'info'
    },

    getStatusText(status) {
      const statusMap = {
        0: '待拣货',
        1: '已拣货',
        2: '已出库'
      }
      return statusMap[status] || '未知状态'
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    // 创建出库单
    handleCreate() {
      this.dialogVisible = true
      this.form = {
        customerId: null,
        supplierId: null,
        productCode: '',
        quantity: 1,
        remark: ''
      }
      this.productOptions = []
    },

    // 提交创建出库单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const res = await request({
              url: '/outbound/create',
              method: 'post',
              data: {
                customerId: this.form.customerId,
                supplierId: this.form.supplierId,
                productCode: this.form.productCode,
                quantity: this.form.quantity,
                remark: this.form.remark
              }
            })
            if (res.code === 200) {
              this.$message.success('创建出库单成功')
              this.dialogVisible = false
              this.fetchData()
            }
          } catch (error) {
            this.$message.error(error.response?.data?.msg || '创建出库单失败')
          }
        }
      })
    },

    // 确认拣货
    async handlePicking(row) {
      try {
        const detailRes = await request({
          url: `/outbound/detail/${row.orderNumber}`,
          method: 'get'
        })

        if (detailRes.code !== 200 || !detailRes.data) {
          this.$message.error('获取出库单详情失败')
          return
        }

        if (detailRes.data.status !== 0) {
          this.$message.warning('该出库单已处理')
          await this.fetchData()
          return
        }

        await this.$confirm('确认已完成拣货?', '提示', {
          type: 'warning'
        })

        const res = await request({
          url: `/outbound/picking/${row.orderNumber}`,
          method: 'post'
        })

        if (res.code === 200) {
          this.$message.success('确认拣货成功')
          await this.fetchData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.response?.data?.msg || '确认拣货失败')
        }
      }
    },

    // 确认出库
    async handleOutbound(row) {
      try {
        const detailRes = await request({
          url: `/outbound/detail/${row.orderNumber}`,
          method: 'get'
        })

        if (detailRes.code !== 200 || !detailRes.data) {
          this.$message.error('获取出库单详情失败')
          return
        }

        if (detailRes.data.status !== 1) {
          this.$message.warning('该出库单未完成拣货或已出库')
          await this.fetchData()
          return
        }

        await this.$confirm('确认要执行出库操作?', '提示', {
          type: 'warning'
        })

        const res = await request({
          url: `/outbound/confirm/${row.orderNumber}`,
          method: 'post'
        })

        if (res.code === 200) {
          this.$message.success('确认出库成功')
          await this.fetchData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.response?.data?.msg || '确认出库失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.outbound-container {
  padding: 20px;
}
.operation-bar {
  margin-bottom: 20px;
}
.el-input-number {
  width: 180px;
}
.el-select {
  width: 100%;
}
</style> 